package com.hdw.common.db;

import com.hdw.common.util.DBUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 动态数据源（数据源切换）
 * Created by hoze on 2017/1/15.
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    private final static Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class);

    private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();

    //线程安全的map，用来存储数据源。
    private static Map<Object, Object> dataSourceMap = new ConcurrentHashMap<>();

    @Override
    protected Object determineCurrentLookupKey() {
        String dataSource = getDataSource();
        return dataSource;
    }

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        dataSourceMap.putAll(targetDataSources);
        super.setTargetDataSources(dataSourceMap);
        super.afterPropertiesSet();// 必须添加该句，否则新添加数据源无法识别到
    }

    public static HikariDataSourceExt getHikariDataSourceById(String id) {
        Object o = dataSourceMap.get(id);
        if (o != null && o.getClass().equals(HikariDataSourceExt.class)) {
            return (HikariDataSourceExt) o;
        } else {
            return null;
        }
    }

    /**
     * 添加新的数据源
     *
     * @param key
     * @param object
     */
    public void addDataSource(String key, Object object) {
        Object put = dataSourceMap.put(key, object);
        super.afterPropertiesSet();// 必须添加该句，否则新添加数据源无法识别到
        DBUtil.closeDataSource(put);
    }

    /**
     * 添加新的数据源
     *
     * @param key
     */
    public void removeDataSource(String key) {
        Object put = dataSourceMap.remove(key);
        super.afterPropertiesSet();// 必须添加该句，否则新添加数据源无法识别到
        DBUtil.closeDataSource(put);
    }

    public static Map<Object, Object> getDataSourceMap() {
        return dataSourceMap;
    }

    /**
     * 设置数据源
     *
     * @param dataSource
     */
    public static void setDataSource(String dataSource) {
        CONTEXT_HOLDER.set(dataSource);
    }

    /**
     * 获取数据源
     *
     * @return
     */
    public static String getDataSource() {
        String dataSource = CONTEXT_HOLDER.get();
        // 如果没有指定数据源，使用默认数据源
        if (null == dataSource) {
            DynamicDataSource.setDataSource(DBUtil.META_DB);
        }
        return CONTEXT_HOLDER.get();
    }

    /**
     * 清除数据源
     */
    public static void clearDataSource() {
        CONTEXT_HOLDER.remove();
    }
}
